package com.zpark.filter;

import com.alibaba.fastjson.JSON;
import com.zpark.common.Content;
import com.zpark.common.R;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter extends HttpFilter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        HttpSession session = req.getSession();
        String requestURI = req.getRequestURI();

        // 放行 /admin/login 请求
        if (requestURI.equals("/MavenDemo01_war/admin/login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 检查会话中是否存在 USER_SESSION_KEY 的数据
        if (session.getAttribute(Content.USER_SESSION_KEY) != null) {
            // 存在，则放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            // 不存在，则返回用户未登录
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().println(JSON.toJSONString(R.error("当前用户未登录")));
        }
    }
}
